﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Oracle = System.Data.OracleClient;
using System.Text;
using System.Data;

namespace FieldUpdater.Classes
{
    public class FieldAssociationLoader : FieldMetadata
    {
        private const string FormParametersKey = "FUFormParameters";
        private const string FormIncludeScriptKey = "FUFormIncludeScript";

        protected override void Render(HtmlTextWriter writer)
        {
            // Registering general page scripts (like initializing current web url on script)
            if (!this.Page.ClientScript.IsClientScriptBlockRegistered(typeof(FieldAssociationLoader), FormParametersKey))
            {
                this.Page.ClientScript.RegisterClientScriptBlock(typeof(FieldAssociationLoader), FormParametersKey, string.Empty);
                this.Controls.Add(new LiteralControl(
                    string.Format(
@"
<script type='text/javascript' src='/_layouts/ManageFieldAssociations/FAScripts.js'></script>
<script type='text/javascript'>EnsureFormParameters('{0}', '{1}');</script>", 
                    this.ListId.ToString("B"), this.Web.Url)));
            }

            // Searching association definitions for current field
            ListDAL listDal = new ListDAL(this.ListId);
            var definitions = listDal.GetDefinitions();
            var currentField = from field in definitions.Associations
                               where field.ChildFieldName == this.Field.Title
                               select field;

            // Creating script for loading this form parameters for the lookup script
            if (currentField != null && currentField.Count() > 0)
            {
                var field = currentField.Single();
                this.Controls.Add(new LiteralControl(string.Format(
                    "<script type='text/javascript'>EnsureSubField('{0}', '{1}');</script>", 
                    field.ParentFieldName, field.ChildFieldName)));
            }

            // Creating script for filling data from an oracle list
            if (definitions.OracleConnections.ContainsKey(this.Field.Title))
            {
                var connectionSettings = definitions.OracleConnections[this.Field.Title];
                using (var _DBConnection = new Oracle.OracleConnection(connectionSettings.ConnectionString))
                {
                    var strQuery = string.Format(
                        OracleConnection.ValuesSelect,
                        connectionSettings.TableName,
                        connectionSettings.SourceColumn);

                    var com = new Oracle.OracleCommand(strQuery, _DBConnection);

                    var da = new Oracle.OracleDataAdapter(com);
                    DataTable dt = new DataTable();
                    da.Fill(dt);

                    var columnValues = (from row in dt.Rows.Cast<DataRow>()
                                        where row[connectionSettings.SourceColumn] != null
                                        select row[connectionSettings.SourceColumn].ToString()).Combine(',');

                    var fieldValue = string.Empty;
                    if (this.ControlMode == SPControlMode.Edit)
                        fieldValue = this.ListItem[this.Field.Title] == null ? string.Empty : this.ListItem[this.Field.Title].ToString();

                    this.Controls.Add(new LiteralControl(string.Format(
                        "<script type='text/javascript'>FillDropDownFirstTime('{0}', '{1}', '{2}');</script>",
                        this.Field.Title, columnValues, fieldValue)));
                }
            }

            base.Render(writer);
        }
    }
}